package com.damai.error;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;


public class ErrorUtil {
	
	public static String printException(Throwable e){
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		PrintStream stream = new PrintStream(outputStream);
		e.printStackTrace(stream);
		stream.close();
		try {
			return new String(outputStream.toByteArray(),"UTF-8");
		} catch (UnsupportedEncodingException e1) {
			return "Not support UnsupportedEncodingException";
		} 
	}
	
	
	public static RuntimeException parseInvocationTargetException(InvocationTargetException e){
		if(e.getTargetException() instanceof RuntimeException){
			return (RuntimeException)e.getTargetException();
		}
		return new RuntimeException(e);
	}
	
	public static RuntimeException wrapThrow(Throwable e){
		if (e instanceof RuntimeException)
            return (RuntimeException) e;
        if (e instanceof InvocationTargetException)
            return wrapThrow(((InvocationTargetException) e).getTargetException());
        return new RuntimeException(e);
		
		
	}
	
}
